/**
 * 
 * @Project le cOeur - Data Virtualization
 * @Date 08.12.2012
 * @Author Aebi Pascal, Kocher Marc
 * @School BFH-TI Biel, Bachelor Thesis
 *
 */

package main.implementation.method;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import main.framework.connector.MySQLConnector;
import main.framework.exception.ResourceMethodExecutionException;
import main.framework.resource.DataGetterResourceMethod;
import main.framework.resource.Resource;
import main.framework.resource.ResourceData;
import main.framework.resource.ResourceURINode;

/**
 * This class gets the current consumption values of a specific index.
 */
public class GetIndexConsumption extends DataGetterResourceMethod {

	private MySQLConnector sqlConnector;
	
	@Override
	public void execute(Resource resource) throws ResourceMethodExecutionException {
		ResourceURINode uriNode = resource.getURINode();
		String previousURINode = resource.getResourceURI().getPreviousNode(uriNode).getUriNode();
		String type = "index";
		String indexID = previousURINode.substring(type.length(), previousURINode.length());
		Calendar calendar = new GregorianCalendar();
		Date date = calendar.getTime();
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
		String time = timeFormat.format(date);
		this.sqlConnector = new MySQLConnector();
		try {
			this.sqlConnector.connect();
			String query = "SELECT `consumptionValue` FROM `consumption` WHERE indexid = " + indexID + " AND time = '" + time + "'";
			List<String[]> data = sqlConnector.executeGetQuery(query);
			super.data = new ResourceData(data, resource);
			this.sqlConnector.disconnect();
		} catch (SQLException e) {
			try {
				Thread.currentThread().sleep(1000);
				this.sqlConnector.connect();
			} catch (Exception e1) {
				throw new ResourceMethodExecutionException(e.getMessage());
			}
		} catch (ClassNotFoundException e) {
			throw new ResourceMethodExecutionException(e.getMessage());
		}
	}

}
